<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Freelancer;
use App\Models\Task;
use App\Models\TaskApplication;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Collection;

class FreelancerController extends Controller
{
    /**
     * 获取自由职业者列表
     */
    public function index(Request $request)
    {
        $tenantId = $request->user()->tenant_id;

        $latestApplicationIds = TaskApplication::where('tenant_id', $tenantId)
            ->selectRaw('MAX(id) as id')
            ->groupBy('freelancer_id');

        $query = TaskApplication::with('freelancer')
            ->whereIn('id', $latestApplicationIds);

        if ($request->filled('name')) {
            $query->where('name', 'like', '%' . $request->name . '%');
        }

        if ($request->filled('phone')) {
            $query->where('phone', 'like', '%' . $request->phone . '%');
        }

        if ($request->filled('id_card')) {
            $query->where('id_card', 'like', '%' . $request->id_card . '%');
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $allowedSortBy = ['name', 'phone', 'status', 'created_at'];
        $sortBy = $request->get('sort_by', 'name');
        if (!in_array($sortBy, $allowedSortBy, true)) {
            $sortBy = 'name';
        }
        $sortOrder = strtolower($request->get('sort_order', 'asc')) === 'desc' ? 'desc' : 'asc';

        $query->orderBy($sortBy, $sortOrder);

        $applications = $query->paginate((int) $request->get('per_page', 15));

        $freelancerIds = $applications->getCollection()->pluck('freelancer_id')->filter()->unique();
        $tasksByFreelancer = $this->loadTaskNamesForFreelancers($tenantId, $freelancerIds);

        $applications->getCollection()->transform(function (TaskApplication $application) use ($tasksByFreelancer) {
            $freelancer = $application->freelancer;
            $freelancerId = $freelancer ? $freelancer->id : null;

            return [
                'id' => $freelancerId,
                'freelancer_id' => $freelancerId,
                'name' => $application->name ?? ($freelancer ? $freelancer->name : ''),
                'phone' => $application->phone ?? ($freelancer ? $freelancer->phone : ''),
                'email' => $freelancer ? $freelancer->email : '',
                'id_card' => $application->id_card ?? ($freelancer ? $freelancer->id_card : ''),
                'bank_account' => $application->bank_account ?? ($freelancer ? $freelancer->bank_account : ''),
                'status' => $application->status,
                'status_label' => $this->mapApplicationStatus($application->status),
                'task_names' => ($freelancerId !== null && isset($tasksByFreelancer[$freelancerId]))
                    ? $tasksByFreelancer[$freelancerId]
                    : [],
                'created_at' => optional($application->created_at)->format('Y-m-d H:i:s'),
                'updated_at' => optional($application->updated_at)->format('Y-m-d H:i:s'),
            ];
        });

        return response()->json([
            'code' => 0,
            'message' => '自由职业者列表获取成功',
            'data' => $applications,
        ]);
    }

    /**
     * 获取单个自由职业者详情
     */
    public function show(Freelancer $freelancer)
    {
        $freelancer->load(['tasks', 'applications.task']);

        return response()->json([
            'code' => 0,
            'data' => $freelancer
        ]);
    }

    /**
     * 更新自由职业者信息
     */
    public function update(Request $request, Freelancer $freelancer)
    {
        $tenantId = $request->user()->tenant_id;
        
        $validator = Validator::make($request->all(), [
            'name' => 'string|max:100',
            'phone' => "string|max:20|unique:freelancers,phone,{$freelancer->id},id,tenant_id,{$tenantId}",
            'email' => "email|unique:freelancers,email,{$freelancer->id},id,tenant_id,{$tenantId}",
            'id_card' => "string|size:18|unique:freelancers,id_card,{$freelancer->id},id,tenant_id,{$tenantId}",
            'bank_account' => 'nullable|string|max:50',
            'bank_name' => 'nullable|string|max:100',
            'gender' => 'nullable|in:male,female',
            'education' => 'nullable|in:junior_high,high_school,college,bachelor,master,doctor',
            'age' => 'nullable|integer|min:16|max:80',
            'resume' => 'nullable|string',
            'status' => 'in:active,inactive',
            'id_card_recognition_status' => 'in:pending,approved,rejected',
            'face_recognition_status' => 'in:pending,approved,rejected',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $freelancer->update($request->all());

        return response()->json([
            'code' => 0,
            'data' => $freelancer,
            'message' => '自由职业者信息更新成功'
        ]);
    }

    /**
     * 删除自由职业者
     */
    public function destroy(Freelancer $freelancer)
    {
        $freelancer->delete();

        return response()->json([
            'code' => 0,
            'message' => '自由职业者删除成功'
        ]);
    }

    /**
     * 批量操作
     */
    public function batchAction(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'action' => 'required|in:activate,deactivate,delete',
            'ids' => 'required|array|min:1',
            'ids.*' => 'integer|exists:freelancers,id'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '参数验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $freelancers = Freelancer::whereIn('id', $request->ids);
        $count = $freelancers->count();

        switch ($request->action) {
            case 'activate':
                $freelancers->update(['status' => 'active']);
                $message = "已激活 {$count} 个自由职业者";
                break;
            case 'deactivate':
                $freelancers->update(['status' => 'inactive']);
                $message = "已停用 {$count} 个自由职业者";
                break;
            case 'delete':
                $freelancers->delete();
                $message = "已删除 {$count} 个自由职业者";
                break;
        }

        return response()->json([
            'code' => 0,
            'message' => $message
        ]);
    }

    private function loadTaskNamesForFreelancers(int $tenantId, Collection $freelancerIds): array
    {
        if ($freelancerIds->isEmpty()) {
            return [];
        }

        return TaskApplication::with('task:id,name')
            ->where('tenant_id', $tenantId)
            ->whereIn('freelancer_id', $freelancerIds)
            ->get()
            ->groupBy('freelancer_id')
            ->map(function ($applications) {
                return $applications
                    ->pluck('task.name')
                    ->filter()
                    ->unique()
                    ->values()
                    ->all();
            })
            ->toArray();
    }

    private function mapApplicationStatus(?string $status): string
    {
        $map = [
            'pending' => '待处理',
            'approved' => '已录用',
            'rejected' => '已拒绝',
            'completed' => '已完成',
            'cancelled' => '已取消',
            'dimission' => '已离岗',
        ];

        return $map[$status] ?? '未知状态';
    }
}
